package artid.com.arttogo.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.VolleyError;

import java.util.ArrayList;
import java.util.List;

import artid.com.arttogo.R;
import artid.com.arttogo.adapter.AuctionComment_Adapter;
import artid.com.arttogo.bean.AuctionCommentParser;
import artid.com.arttogo.bean.OneStateIntParser;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.view.MyEditText;
import artid.com.arttogo.view.pulllist.PullToRefreshLayout;
import artid.com.arttogo.view.pulllist.PullableListView;

import static artid.com.arttogo.R.id.imagedot_message;
import static artid.com.arttogo.app.ArtToGoApp.getActivity;

/**
 *
 *
 * 项目名称：ArtworkArt   
 * 类名称：AuctionComment_Activity   
 * 类描述：评论   
 * 创建人：耿卫斌   
 * 创建时间：2017-3-6 下午2:22:49   
 *
 */
public class AuctionComment_Activity extends BaseActivity implements OnClickListener {
	private PullableListView mListView;
	private PullToRefreshLayout mPullLayout;
	private MyEditText replyEd;
	private TextView sendBtn;
	private RatingBar mRatingBar;
	private LinearLayout ratingBarLL;
	private boolean isRefreshed = false;// 是否刷新
	private int page = 1;
	private AuctionComment_Adapter mAdapter;
	private RelativeLayout activityRootView;   //Activity最外层的Layout视图
	private String ID;//请求评论列表使用的ID（可以是拍卖会id,专场id,拍品id）
	private String Type;//请求评论列表使用的类型	type	1,机构，2，拍卖会，3专场，4拍品
	private int score;//发表评论-评分
	private LinearLayout noDataLL;
	private List<AuctionCommentParser> list=new ArrayList<AuctionCommentParser>();
	private List<AuctionCommentParser> more_list=new ArrayList<AuctionCommentParser>();
	private int replyPosition=-1;//-1的时候为评论反之都是评论
	private String replyID;//回复ID
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_auctioncomment);
		initView();
	}

	private void initView(){
		IntentFilter filter = new IntentFilter("com.AuctionComment_Activity.receiver");
		registerReceiver(broadcastReceiver, filter);
		mContext=AuctionComment_Activity.this;
		ID=getIntent().getStringExtra("ID");
		Type=getIntent().getStringExtra("Type");
		mBack = (ImageView) findViewById(R.id.back_btn);
		mBack.setOnClickListener(this);
		mTittle = (TextView) findViewById(R.id.tittle_text);
		mTittle.setText("评论");
		activityRootView=(RelativeLayout) findViewById(R.id.AuctionComment_activityRootView);
		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobal);
		mListView = (PullableListView) findViewById(R.id.AuctionComment_ListView);
//		mListView.setOnItemClickListener(onItemClick);//目前是已经去掉了（因为改UI去掉了，可以直接删除点击事件）
		noDataLL = (LinearLayout) findViewById(R.id.ll_hint);
		mPullLayout = (PullToRefreshLayout) findViewById(R.id.AuctionComment_refresh_view);
		replyEd=(MyEditText) findViewById(R.id.AuctionComment_replyEd);
		replyEd.setOnEditorActionListener(onEditorAction);
		sendBtn=(TextView) findViewById(R.id.AuctionComment_sendBtn);
		sendBtn.setOnClickListener(this);
		ratingBarLL=(LinearLayout) findViewById(R.id.AuctionComment_ratingBarLL);
		ratingBarLL.setVisibility(View.GONE);
		mRatingBar=(RatingBar) findViewById(R.id.AuctionComment_ratingBar);
		mRatingBar.setOnRatingBarChangeListener(onRatingBar);
		mPullLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {

			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				// 下拉刷新
				page = 1;
				isRefreshed = true;
				getData();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				// 上拉加载
				page++;
				getData();
			}
		});
		getData();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
			case R.id.back_btn:
				finish();
				break;
			case R.id.AuctionComment_sendBtn:
				//发送信息
				if(!TextUtils.isEmpty(replyEd.getText().toString().trim())){
					if(replyPosition==-1){
						sendComment();
					}else{
						replyComment();
					}
				}else{
					ToastUtil.toast(mContext, "您似乎忘了点什么");
				}
				break;

			default:
				break;
		}
	}

	/**
	 * 列表Item点击
	 */
	OnItemClickListener onItemClick=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int position,
								long arg3) {
			// TODO Auto-generated method stub
			commentPopupWindow(v,position);
		}
	};

	/**
	 * 星级评论监听
	 */
	OnRatingBarChangeListener onRatingBar=new OnRatingBarChangeListener() {

		@Override
		public void onRatingChanged(RatingBar ratingBar, float rating,
									boolean fromUser) {
			// TODO Auto-generated method stub
			score=(int)rating;
		}
	};

	/**
	 * 监听软件盘是否弹出
	 */
	OnGlobalLayoutListener onGlobal=new OnGlobalLayoutListener() {

		@Override
		public void onGlobalLayout() {
			// TODO Auto-generated method stub
			int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
			if (heightDiff > 300)
			{
				// 说明键盘是弹出状态
				ratingBarLL.setVisibility(View.VISIBLE);
			} else{
				ratingBarLL.setVisibility(View.GONE);
				//输入为空的时候当软件盘收起将回复事件关闭恢复评论
				if(TextUtils.isEmpty(replyEd.getText().toString())){
					replyPosition=-1;//恢复状态
					replyEd.setHint("评论:");
				}
			}
		}
	};

	/**
	 * 软键盘回车按钮的监听
	 */
	OnEditorActionListener onEditorAction=new OnEditorActionListener() {

		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event)  {
			final String searchStr = replyEd.getText().toString().trim();
			if (actionId== EditorInfo.IME_ACTION_SEARCH ||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)) {
				//do something;    
				if(searchStr == null || "".equals(searchStr)){
					ToastUtil.toast(mContext, "您似乎忘了点什么");
					return true;
				}else{
					if(replyPosition==-1){
						sendComment();
					}else{
						replyComment();
					}
				}
				return false;
			}
			return false;
		}
	};

	/**
	 * 关闭软键盘
	 * @param mContext
	 */
	public  void showKeyboard(Context mContext){
		InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
	}

	/**
	 * 评论列表PopupWindow
	 */
	private LinearLayout popupWindowreportLL;
	private TextView popupWindowDelete,popupWindowReply,popupWindowCancel;
	private void commentPopupWindow(View v, final int position){
		LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View mView = layoutInflater.inflate(R.layout.pop_comment, null);// 自定义的布局文件
		popupWindowreportLL= (LinearLayout) mView.findViewById(R.id.cmt_reportLL);
		popupWindowDelete = (TextView) mView.findViewById(R.id.cmt_report);
		popupWindowDelete.setText("删除");
		if(more_list.get(position).getIsme()==1){
			//该评论如果是自己评论的可以删除反之不可以
			popupWindowreportLL.setVisibility(View.VISIBLE);
		}else{
			popupWindowreportLL.setVisibility(View.GONE);
		}
		popupWindowReply = (TextView) mView.findViewById(R.id.cmt_reply);
		popupWindowCancel = (TextView) mView.findViewById(R.id.cmt_cancel);
		final PopupWindow mPopupWindow = new PopupWindow(mView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		mPopupWindow.setOutsideTouchable(true);
		popupWindowDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//删除
				deleteComment(position);
				mPopupWindow.dismiss();
			}
		});
		popupWindowReply.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//回复
				if(!TextUtils.isEmpty(AppUtil.getUser().getUid())){
					if(!AppUtil.getUser().getUid().equals(more_list.get(position).getUid())){
						replyPosition=position;
						showKeyboard(mContext);
						replyEd.setHint("@"+more_list.get(position).getRealname());
						replyID=more_list.get(position).getMessid();
					}else{
						ToastUtil.toast(mContext, "您不能自己回复自己哦");
					}
				}else{
					AppUtil.Logout(mContext);
					AppUtil.LoginVer(mContext);
				}
				mPopupWindow.dismiss();
			}
		});
		popupWindowCancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//取消
				mPopupWindow.dismiss();
			}
		});
		int[] location = new int[2];
		v.getLocationOnScreen(location);
		mPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]+v.getWidth(), location[1]);
	}

	/**
	 * 获取评论列表
	 * id	也可以是拍卖会id,专场id,拍品id
	 页码	page
	 条数	pagesize
	 类型	type	1,机构，2，拍卖会，3专场，4拍品
	 */
	private void getData(){
		VolleyBasic.getInstance(this).post(Cache.auction_CommentList,
				VolleyMap.getInstance().auction_CommentList(page, 10, ID, Type),
				AuctionCommentParser.class, new VolleyCallback() {

					@SuppressWarnings({ "unchecked", "static-access" })
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						mPullLayout.loadmoreFinish(mPullLayout.SUCCEED);
						list=(List<AuctionCommentParser>) vd.getList();
						if (isRefreshed == true) {
							more_list.clear();
							isRefreshed = false;
						}
						if (!list.isEmpty()) {
							more_list.addAll(list);
						}

						//这里是显示有数据和无数据的布局
						if(more_list!=null && more_list.size()!=0){
							noDataLL.setVisibility(View.GONE);
						}else{
							noDataLL.setVisibility(View.VISIBLE);
							return;
						}

						if (mAdapter == null) {
							mAdapter=new AuctionComment_Adapter(mContext,Type, more_list);
							mListView.setAdapter(mAdapter);
						}
						mAdapter.notifyDataSetChanged();
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						mPullLayout.loadmoreFinish(mPullLayout.FAIL);
						//这里是显示有数据和无数据的布局
						if(more_list!=null && more_list.size()!=0){
							noDataLL.setVisibility(View.GONE);
						}else{
							noDataLL.setVisibility(View.VISIBLE);
							return;
						}
					}
				});
	}

	/**
	 * 发表评论
	 * 机构id	id	也可以是拍卖会id,专场id,拍品id
	 评论类型	type	1,机构，2，拍卖会，3专场，4拍品
	 评论内容	content
	 评分			score 1-5分
	 */
	private void sendComment(){
		VolleyBasic.getInstance(this).post(Cache.replyComment,
				VolleyMap.getInstance().replyComment(ID, Type,replyEd.getText().toString(),score),
				OneStateIntParser.class, new VolleyCallback() {

					@SuppressWarnings({ "unchecked", "static-access" })
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						OneStateIntParser bean=(OneStateIntParser) vd.getData();
						if(bean.getState()==1){
							ToastUtil.toast(mContext, "发送成功");
							replyEd.setText("");
							mRatingBar.setRating(0);
							page = 1;
							isRefreshed = true;
							VolleyBasic.getInstanceNoDialog(AuctionComment_Activity.this);
							getData();
						}else{
							ToastUtil.toast(mContext, "发送失败");
						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						ToastUtil.toast(mContext, "发送失败");
					}
				});
	}

	/**
	 * 回复评论
	 * id	id	机构/拍卖会/专场/拍品的id
	 用户口令	token
	 内容	content
	 回复那条评论的id	commentid
	 类型	type	1,机构，2，拍卖会，3专场，4拍品
	 评分	score	评分范围0-5
	 */
	private void replyComment(){
		VolleyBasic.getInstance(this).post(Cache.Answercomment,
				VolleyMap.getInstance().Answercomment(ID, Type,replyID,replyEd.getText().toString(),score),
				OneStateIntParser.class, new VolleyCallback() {

					@SuppressWarnings({ "unchecked", "static-access" })
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						OneStateIntParser bean=(OneStateIntParser) vd.getData();
						if(bean.getState()==1){
							ToastUtil.toast(mContext, "发送成功");
							replyPosition=-1;//恢复状态
							replyEd.setText("");
							replyEd.setHint("评论:");
							mRatingBar.setRating(0);
							page = 1;
							isRefreshed = true;
							VolleyBasic.getInstanceNoDialog(AuctionComment_Activity.this);
							getData();
						}else{
							ToastUtil.toast(mContext, "发送失败");
						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						ToastUtil.toast(mContext, "发送失败");
					}
				});
	}

	/*
	 * 删除评论
	 * ID 评论id
	 * 类型	type	1,机构，2，拍卖会，3专场，4拍品
	 */
	private void deleteComment(final int position){
		VolleyBasic.getInstance(this).post(Cache.delComment,
				VolleyMap.getInstance().delComment(more_list.get(position).getMessid(), Type),
				OneStateIntParser.class, new VolleyCallback() {

					@SuppressWarnings({ "unchecked", "static-access" })
					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						OneStateIntParser bean=(OneStateIntParser) vd.getData();
						if(bean.getState()==1){
							more_list.remove(position);
							mAdapter.notifyData(more_list);
							ToastUtil.toast(mContext, "删除成功");
						}else{
							ToastUtil.toast(mContext, "删除失败");
						}
					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub
						ToastUtil.toast(mContext, "删除失败");
					}
				});
	}

	//广播接收器
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getBooleanExtra("isReply", false)) {
				//判断是否为适配器发送的回复推送
				int position=intent.getIntExtra("Position",-1);
				if(position!=-1) {
					if (!TextUtils.isEmpty(AppUtil.getUser().getUid())) {
						replyPosition = position;
						showKeyboard(mContext);
						replyEd.setHint("@" + more_list.get(position).getRealname());
						replyID = more_list.get(position).getMessid();
					} else {
						AppUtil.Logout(mContext);
						AppUtil.LoginVer(mContext);
					}
				}
			};
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 关闭广播
		unregisterReceiver(broadcastReceiver);
	}
}
